package by.alex.dzeshko.facebooksuperclient.service;

import org.json.JSONException;
import org.json.JSONObject;
import by.alex.dzeshko.facebooksuperclient.R;
import by.alex.dzeshko.facebooksuperclient.async.LoadJsonObjectAsyncTask;
import by.alex.dzeshko.facebooksuperclient.async.common.ParamCallback;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;
import android.content.ContentValues;
import android.content.Intent;
import android.util.Log;

public class ProfileService extends CommonService<JSONObject> implements ParamCallback<JSONObject>{
	
	public static final String ACTION_ON_ERROR = "by.alex.dzeshko.facebooksuperclient.service.ProfileService.ACTION_ON_ERROR";
	
	public static final String ACTION_ON_SUCCESS = "by.alex.dzeshko.facebooksuperclient.service.ProfileService.ACTION_ON_SUCCESS";

	private static final String LOG_TAG = "ProfileService";

	@Override
	protected void handleCommand(Intent intent) {
		super.handleCommand(intent);
		new LoadJsonObjectAsyncTask(this).start(requestBuilder);
	}

	@Override
	public void onSuccess(JSONObject p) {
		onHandleResponse(p);
	}
	
	@Override
	public void onError(Throwable e) {
		Log.e(LOG_TAG,e.toString());
		Intent intent = new Intent(ACTION_ON_ERROR);
		intent.putExtra(EXTRA_KEY_MESSAGE, e.toString());
		sendBroadcast(intent);
	}
	
	@Override
	protected void threadedHandleResponse(JSONObject response) {
		if(response.has(getString(ERROR))){
			JSONObject err;
			try {
				err = response.getJSONObject(getString(ERROR));
				String errMessage = err.getString(getString(MESSAGE));
				Log.e(err.getString(getString(TYPE)),errMessage);
				onError(new Throwable(errMessage));
				return;
			} catch (JSONException e) {
				onError(e);
			}
		}
		final ContentValues contentValues = new ContentValues();
		contentValues.put("data", response.toString());
		getContentResolver().insert(FbContract.UserProfileColumns.USER_PROFILE_CONTENT_URI, contentValues);
		Intent intent = new Intent(ACTION_ON_SUCCESS);
		sendBroadcast(intent);
		
	}

}
